var express = require('express');
var morgan = require('morgan');
var path = require('path');
var fs = require('fs');
var cookieParser = require('cookie-parser');
// 模块路由
var router = express.Router();

var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});

router.use(cookieParser());
router.use(morgan('combined', {stream: accessLogStream}));

/* GET home page. */
router.get('/', function(req, res, next) {
  if (req.headers.cookie) {
    console.log('解析前的cookie：'+req.headers.cookie);
  }
  //读取cookie
  var visit = req.cookies.visit || 0;
  //设置cookie
  res.cookie('visit', ++visit, {maxAge: 60000});
  // res.send("您已访问：" + visit + '次');
  res.render('index', { title: 'Express' });
});

/* 网站首页接受 POST 请求 */
router.post('/', function(req, res, next) {
  res.send('Got a POST request');
});

// 路由句柄 提供多个回调函数
router.get('/mutil', function(req, res, next) {
  console.log("first callback!");
  next();
}, function(req, res, next) {
  res.send('second callback!');
});

// 链式路由句柄
router.route('/route')
  .get(function(req, res) {
    console.log("参", req.params);
    res.send('route get');
  })
  .post(function(req, res) {
    res.send('route post');
  })

router.put('/', function(req, res, next) {
  res.send('Got a PUT request');
});

router.get('/hello', function(req, res, next) {
  res.send('Hello World!');
});


module.exports = router;
